package com.situ.shoplookweb.api;

import com.situ.shoplook.common.mapper.ShoppingCartMapper;
import com.situ.shoplook.common.model.ShoppingCart;
import com.situ.shoplook.common.model.User;
import com.situ.shoplookweb.service.ShoppingCartService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author xinchen
 * @Date: 2024/09/05/ 16:27
 * @Description 跳转购物车
 */

@RestController
public class ShopCatApi {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 添加购物车
     * @return
     */
    @PostMapping("/shop-cart")
    public Map<String,Object> addShoppingCart(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
        User user = (User) session.getAttribute("newBeeMallUser");
        // 清空购物车缓存
        session.removeAttribute("shopCartItems");
        /**
         * 添加到购物车中
         */
        shoppingCart.setUserId(user.getUserId());
        int result = shoppingCartService.addShoppingCart(shoppingCart,session);
        if (result < 1) {
            return Map.of("code", 500, "msg", "添加失败");
        }
        /**
         * 该用户的购物车总数
         */
        int count = this.shoppingCartMapper.findByUserIdCount(user.getUserId());
        session.setAttribute("shopCartItemCount",count);
        return Map.of("code", 200, "msg", "添加成功");
    }

    /**
     * 修改购物车
     */
    @PutMapping("/shop-cart")
    public Map<String,Object> updateShoppingCart(@RequestBody ShoppingCart shoppingCart, HttpSession session) {
        User user = (User) session.getAttribute("newBeeMallUser");
        shoppingCart.setUserId(user.getUserId());
        int result = shoppingCartService.updateShoppingCart(shoppingCart,session);
        /**
         * 修改成功
         */
        if (result < 1) {
            return Map.of("code", 500, "msg", "修改失败");
        }

        return Map.of("code", 200, "msg", "修改成功");
    }
    /**
     * 删除购物车
     */
    @DeleteMapping("/shop-cart/{cartId}")
    public Map<String,Object> deleteShoppingCart(@PathVariable("cartId") Long cartId,HttpSession session) {

        int result = shoppingCartService.deleteShoppingCart(cartId,session);
        /**
         * 删除成功
         */
        if (result < 1) {
            return Map.of("code", 500, "msg", "删除失败");
        }
        return Map.of("code", 200, "msg", "删除成功");
    }
}
